﻿using System;
using System.Configuration;
using System.Linq;
using Controllers;

namespace Web
{
    public partial class EmpFamEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string id = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(id) && id != "undefined")
                {
                    ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);

                    var q = ctx.EmpFamilies.Single(r=>r.Id== int.Parse(id));
                    txtName.Value = q.Name;
                    txtRelation.Value = q.Relation;
                    txtPhone.Value = q.ContactPhone;
                    txtWork.Value = q.WorkUnit;                    
                    txtAddress.Value = q.ContactAddress;
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            string id = Request.QueryString["id"];
            EmpFamily empFamily;
            if (!string.IsNullOrEmpty(id) && id != "undefined")
            {
                empFamily = ctx.EmpFamilies.Single(r => r.Id == int.Parse(id));
            }
            else
            {
                empFamily = new EmpFamily();
                empFamily.EmpId = int.Parse(Request.QueryString["empId"]);
                ctx.EmpFamilies.InsertOnSubmit(empFamily);
            }
            empFamily.Relation = txtRelation.Value.Trim();
            empFamily.Name = txtName.Value.Trim();
            empFamily.WorkUnit = txtWork.Value.Trim();
            empFamily.ContactPhone = txtPhone.Value.Trim();
            empFamily.ContactAddress = txtAddress.Value.Trim();

            ctx.SubmitChanges();
            Response.Write("<script>window.returnValue='" + empFamily.Id + "';window.close();</script>");
        }
    }
}